<template>
  <TabHead/>

  <div class="box">
    <h1 style="text-align: center">登录</h1>
    <el-form size="large" :rules="rules" :model="user" ref="ruleFormRef">
      <el-form-item prop="user_id">
        <el-input v-model="user.user_id"/>
      </el-form-item>
      <el-form-item prop="pwd">
        <el-input v-model="user.pwd" show-password/>
      </el-form-item>
      <el-button type="primary" style="width: 100%" @click="login">
        登录
      </el-button>
      <el-button type="warning" style="width: 100%;margin-left: 0;margin-top: 11px" @click="toRegist">
        先去注册
      </el-button>
    </el-form>
  </div>
</template>

<script setup>
import {getCurrentInstance, reactive} from 'vue'
import {ElMessage} from "element-plus";
import request from "../request";
import {useRouter} from "vue-router";
import TabHead from "../components/TabHead.vue";

//创建对象user
const user = reactive({})

//定义表单校验规则
const rules = reactive({
  user_id: [
    {required: true, message: '请输入用户名', trigger: 'blur'}
  ],
  pwd: [
    {required: true, message: '请输入密码', trigger: 'blur'}
  ]
})

// Promise
// 往后台发请求 http://localhost:9090
const {proxy} = getCurrentInstance()
const router = useRouter();

const login = () => {
  proxy.$refs.ruleFormRef.validate((valid) => {
    if (valid) {
      request.post('/user/login', user).then((res) => {
        if (res.success === 1) {
          localStorage.setItem("token",res.token)
          localStorage.setItem("success",res.success)
          localStorage.setItem("username",res.username)
          localStorage.setItem("user_id",res.user_id)

          ElMessage({
            message: '登录成功',
            type: 'success',
          })

          router.go(-1)
        } else if(res.success === 0)
        {
          ElMessage.error('用户名或密码错误')
        }
      })

    }
  })
}

//转跳到注册页
const toRegist = () => {
  router.push("/regist")
}
</script>

<style>
.box {
  width: 500px;
  margin: 150px auto;
}

</style>

